import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Question } from '../../entity/Question';
import { QuestionDetail } from '../../entity/QuestionDetail';
import { NzMessageService } from 'ng-zorro-antd';
import { UserService } from '../../services/user.service';
import { User } from '../../entity/User';

@Component({
  selector: 'app-question-detail',
  templateUrl: './question-detail.component.html',
  styleUrls: ['./question-detail.component.css']
})
export class QuestionDetailComponent implements OnInit {
  detaiId: number;
  user: User;
  data: Question = new Question();
  answers: Array<QuestionDetail> = new Array<QuestionDetail>();
  inputValue: string;

  constructor(private route: ActivatedRoute
    , private http: HttpClient
    , private userService: UserService
    , private router: Router
    , private message: NzMessageService) { }

  ngOnInit() {
    this.user = this.userService.getUser();

    this.route.params.subscribe((params) => {
      this.detaiId = params.id;

      this.http
        .get(`/api/Questions/findById?aLong=${this.detaiId}`)
        .subscribe(response => {
          this.data = response as Question;
        });

      this.http
        .get(`/api/QuestionDetail/findByQuestionId?id=${this.detaiId}`)
        .subscribe(response => {
          this.answers = response as Array<QuestionDetail>;
        });
    });
  }

  submit() {
    if (this.inputValue == null || this.inputValue == '') {
      this.message.error('回答不能为空');
      return;
    }

    const answer = new QuestionDetail();
    answer.answerUser = this.user.name;
    answer.questionId = this.detaiId;
    answer.answer = this.inputValue;

    this.http
      .post(`/api/QuestionDetail/insert`, JSON.stringify(answer), {
        headers: new HttpHeaders({
          'Content-type': 'application/json'
        })
      })
      .subscribe(response => {
        if (!response as boolean) {
          this.message.error('回答失败');
        } else {
          this.http
            .get(`/api/QuestionDetail/findByQuestionId?id=${this.detaiId}`)
            .subscribe(item => {
              this.answers = item as Array<QuestionDetail>;
              this.inputValue = '';
            });
        }
      });
  }
}
